<template>
	<view class="bg-white px-3">
		<u-form label-width="200" :model="form" ref="uForm" label-position="top">
			<div class="flex flex-column">
				<div class="flag-title light-color">基础信息</div>
				<u-form-item required :border-bottom="false" prop="goods_name" label="商品名称"><u-input v-model="form.goods_name"
						:custom-style="defaultInputStyle" /></u-form-item>
				<u-form-item required :border-bottom="false" prop="goods_classify_id" label="商品分类">
					<view class="flex align-center border w-100 px-2 bgf7f7f7 rounded" @click="typeshow = true">
						<text class="flex-1 fs-28">{{form.goods_classify_id?form.classText:'选择商品分类'}}</text>
						<u-icon class="ft999999" name="arrow-down"></u-icon>
					</view>
					<u-select v-model="typeshow" mode="mutil-column-auto" confirm-color="#e87722" :list="typeList" value-name="id"
						label-name="gd_c_name" @confirm="confirmType"></u-select>
				</u-form-item>
				<u-form-item :border-bottom="false" prop="brand" label="商品品牌"><u-input v-model="form.brand"
						:custom-style="defaultInputStyle" /></u-form-item>
				<div class="flag-title light-color">价格信息</div>
				<u-form-item required :border-bottom="false" prop="day_amount" label="日租金额(元)"><u-input
						v-model="form.day_amount" :custom-style="defaultInputStyle" /></u-form-item>
				<u-form-item required :border-bottom="false" prop="deposit_amount" label="押金金额(元)"><u-input
						v-model="form.deposit_amount" :custom-style="defaultInputStyle" /></u-form-item>
				<u-form-item required :border-bottom="false" prop="buyed_amount" label="买断金额(元)"><u-input
						v-model="form.buyed_amount" :custom-style="defaultInputStyle" /></u-form-item>
				<div class="flag-title light-color">详情信息</div>
				<u-form-item required :border-bottom="false" prop="main_image" label="商品主图">
					<u-upload :file-list="main_image" :header="{ 'ba-user-token': storage.getAccessToken(),server:true }"
						:action="action" width="200" @on-uploaded="onUploaded($event, 'main_image')" :max-count="1"
						:show-progress="false" @on-remove="removemainimage"></u-upload>
				</u-form-item>
				<u-form-item required :border-bottom="false" prop="images" label="商品幻灯片">
					<u-upload :file-list="images" :header="{ 'ba-user-token': storage.getAccessToken(),server:true }"
						:action="action" width="200" @on-uploaded="onUploaded($event, 'images')" :max-count="6"
						:show-progress="false" @on-remove="removeImages"></u-upload>
				</u-form-item>

				<u-form-item required :border-bottom="false" prop="detail_info" label="商品描述">

				</u-form-item>
				<view class="bgf7f7f7 p-2 rounded htmlContent" style="max-height: 600px;" v-html="htmlContent"
					@click="navTo('/pages/store/goodsEdit')"></view>


				<!-- <view class="flex flex-column">
					<view class="mb-2 fs-28">状态设置</view>
					<view class="flex align-center justify-between fs-24 ft666666">
						<text>审核通过后立即上架</text>
						<u-switch v-model="form.checked" active-color="#e87722" inactive-color="#999" size="40"></u-switch>
					</view>
				</view> -->
			</div>
		</u-form>
		<u-gap height="150" bg-color="#fff"></u-gap>
		<view class="position-fixed bottom-0 left-0 right-0">
			<div class="rounded-circle text-center py-2 bge87722cc text-white fs-32 mx-3" @click="validatorStep1Form">提交审核
			</div>
			<u-gap height="40" bg-color="#fff"></u-gap>
		</view>
	</view>
</template>

<script>
	import storage from "@/utils/storage.js";
	import {
		upload
	} from "@/api/common.js";
	import {
		createGoods,
		storeGoodsDetails,
		goodsUpdate
	} from "@/api/store.js";
	import {
		getCategoryList
	} from "@/api/goods.js";
	export default {
		data() {
			return {
				htmlContent: '',
				storage,
				action: upload, //图片上传数据
				defaultInputStyle: {
					background: "#f7f7f7",
					padding: "0 20rpx",
					"border-radius": "10rpx",
				},
				form: {
					goods_name: '',
					goods_classify_id: '',
					classText: '',
					day_amount: '',
					deposit_amount: '',
					detail_info: '',
					buyed_amount: '',
					images: [],
					main_image: [],
					checked: false
				},
				images: [],
				main_image: [],
				typeList: [],
				typeshow: false,
				goodsDetails: {},
				id: null
			}
		},
		onLoad(query) {
			this.id = query.id || ''
		},
		onShow() {
			const goods_100 = uni.getStorageSync('goods_100')
			if (goods_100) {
				this.htmlContent = goods_100
				uni.removeStorageSync('goods_100')
			}
			console.log(goods_100)
		},
		created() {
			this.getCategoryList()
		},
		methods: {
			navTo(url) {
				uni.setStorageSync('goods_htmlContent', this.htmlContent)
				setTimeout(() => {
					uni.navigateTo({
						url
					})
				})
			},
			storeGoodsDetails() {
				storeGoodsDetails({
					id: this.id
				}).then(res => {
					this.goodsDetails = res.data.data.goods
					this.form = {
						...this.goodsDetails,
						classText: this.findCategoryAndCombine(this.typeList, this.goodsDetails.goods_classify_id),
						main_image: [this.goodsDetails.main_image]
					}
					this.htmlContent = this.goodsDetails.detail_info
					this.images = this.goodsDetails.images.map(item => {
						return {
							url: item
						}
					})
					console.log('this.images', this.images)
					this.main_image = [{
						url: this.goodsDetails.main_image
					}]
				})
			},
			findCategoryAndCombine(jsonData, targetId) {
				// 递归遍历函数
				function traverse(items, parentName = null) {
					for (const item of items) {
						// 检查当前项是否是目标
						if (item.id === targetId) {
							// 如果有父名称则组合，否则只返回当前名称
							return parentName ? `${parentName}/${item.gd_c_name}` : item.gd_c_name;
						}

						// 如果有子项，递归查找
						if (item.children && item.children.length > 0) {
							const result = traverse(item.children, item.gd_c_name);
							if (result) {
								return result;
							}
						}
					}
					return null; // 未找到
				}

				return traverse(jsonData);
			},
			confirmType(val) {
				this.form.goods_classify_id = val[val.length - 1].value
				this.form.classText = val.map(item => item.label).join('/')
			},
			getCategoryList() {
				getCategoryList().then(res => {
					this.typeList = res.data.data.list
					if (!this.id) return
					this.storeGoodsDetails()
				})
			},
			onUploaded(lists, key) {
				let images = [];
				if (!this.form[key]) {
					this.form[key] = [];
				}
				console.log(lists)
				const list = lists.filter(item => item.response)
				list.forEach((item) => {
					images.push(item.response.data.file.url);
				});
				// console.log(images, key)
				if (key === 'main_image') {
					this.form[key] = images
					return
				}
				this.form[key].push(...images);
				// console.log(this.form)
			},
			removeImages(index) {
				this.form['images'].splice(index, 1)
			},
			removemainimage(index) {
				this.form['main_image'].splice(index, 1)
			},
			validatorStep1Form() {
				this.$refs.uForm.validate(async (valid) => {
					console.log(valid);
					if (valid) {
						this.createGoods()
					}
				});
			},
			createGoods() {
				const params = {
					...this.form
				};
				params.main_image = this.form.main_image.join(',')
				params.detail_info = this.htmlContent
				// console.log(params, this.form.main_image)
				if (params.id) {
					this.goodsUpdate(params)
					return
				}

				createGoods(params).then(res => {
					const data = res.data
					if (data.code !== 1) {
						uni.showToast({
							title: data.msg,
							icon: 'none'
						})
						return
					}
					uni.showToast({
						title: '创建商品成功'
					})
					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/store/goodsManage'
						})
					}, 1500)
				})
			},
			goodsUpdate(params) {
				goodsUpdate(params).then(res => {
					const data = res.data
					if (data.code !== 1) {
						uni.showToast({
							title: data.msg,
							icon: 'none'
						})
						return
					}
					uni.showToast({
						title: data.msg
					})
					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/store/goodsManage'
						})
					}, 1500)
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.column {
		padding: 32rpx;
		margin-bottom: 20rpx;
		background: #fff;
	}

	.tips {
		color: #999;
		font-size: 24rpx;
		line-height: 1.2;
		margin-top: 10rpx;
	}

	.flag-title {
		font-size: 42rpx;
		font-weight: bold;
	}

	.submit,
	.notice {
		font-weight: bold;
		font-size: 28rpx;

		height: 92rpx;
		text-align: center;
		letter-spacing: 4rpx;
		line-height: 92rpx;
		border-radius: 20rpx;
	}

	.wrapper {
		padding: 16rpx;
	}
</style>